# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def openLock(self, deadends: List[str], target: str) -> int:
        step_dict = {
            '0': ['9', '1'],
            '1': ['0', '2'],
            '2': ['1', '3'],
            '3': ['2', '4'],
            '4': ['3', '5'],
            '5': ['4', '6'],
            '6': ['5', '7'],
            '7': ['6', '8'],
            '8': ['7', '9'],
            '9': ['8', '0']
        }

        def move_next(source_step: str) -> List[str]:
            steps = []
            for index, ch in enumerate(source_step):
                for i in range(2):
                    next_step = list(source_step[:])
                    next_step[index] = step_dict.get(ch)[i]
                    steps.append(''.join(next_step))
            return steps

        dead_ends_dict = {}
        for item in deadends:
            dead_ends_dict[item] = 1

        search_queue = [["0000", 0]]
        steps_set = set()
        steps_set.add('0000')
        ans = 10000

        while len(search_queue) > 0:
            current_steps = search_queue.copy()
            search_queue.clear()

            for step in current_steps:
                if step[0] in dead_ends_dict:
                    continue

                news_step = move_next(step[0])
                for new_step in news_step:
                    if new_step in steps_set:
                        continue

                    if new_step == target:
                        ans = min(step[1] + 1, ans)
                        return ans

                    if new_step in dead_ends_dict:
                        continue

                    steps_set.add(new_step)
                    search_queue.append([new_step, step[1] + 1])

        if ans == 10000:
            ans = -1
        return ans


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        (["8888"], "0009", 1),
        (["0201", "0101", "0102", "1212", "2002"], "0202", 6),
        (["8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"], '8888', -1),
        (["0000"], '8888', -1)
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果

        input1 = case_item[0]
        input2 = case_item[1]

        expect = case_item[len(case_item) - 1]
        exec_result = solution.openLock(input1, input2)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

